﻿using GamFi.API.Application.Contracts.Image.GetImageById;
using GamFi.API.Application.Exceptions;
using GamFi.API.Application.Interfaces;
using GamFi.API.Application.Resources;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;

namespace GamFi.API.Application.Features.Queries.Image.GetImageById;

/// <summary>
/// Обработчик для <see cref="GetImageByIdQuery"/>
/// </summary>
public class GetImageByIdQueryHandler(IDbContext dbContext, IS3Service s3Service, IStringLocalizer<ExceptionMessages> localizer)
    : IRequestHandler<GetImageByIdQuery, GetImageByIdResponse>
{
    /// <inheritdoc />
    public async Task<GetImageByIdResponse> Handle(GetImageByIdQuery request, CancellationToken cancellationToken)
    {
        if (request is null)
            throw new RequestException(localizer[nameof(RequestException.RequestIsEmpty)]);

        var image = await dbContext.Images.FirstOrDefaultAsync(x => x.Id == request.ImageId, cancellationToken);

        if (image is null)
            throw new ImageException(localizer[nameof(ImageException.ImageByIdNotFound)]);

        var imageFromS3 = await s3Service.DownloadFileAsync(image.Address, cancellationToken: cancellationToken);

        if (imageFromS3 is null)
            throw new ImageException(localizer[nameof(ImageException.ImageByIdNotFound)]);

        using var memoryStream = new MemoryStream();
        await imageFromS3.Content.CopyToAsync(memoryStream, cancellationToken);

        return new GetImageByIdResponse(
            content: memoryStream.ToArray(),
            contentType: imageFromS3.ContentType,
            fileName: imageFromS3.FileName);
    }
}